package com.gisterrier.client.components;

import java.util.ArrayList;
import java.util.TreeMap;

import com.common.shared.map.GisMapClickedObject;
import com.gisterrier.shared.GissTigerConstants;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.widgets.events.DoubleClickEvent;
import com.smartgwt.client.widgets.events.DoubleClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;

public class PMapObjects extends HLayout {

	private ListGrid lgCustomes = new ListGrid();
	private TreeMap<String, GisMapClickedObject> map = new TreeMap<String, GisMapClickedObject>();

	public PMapObjects() {

		lgCustomes = new ListGrid();
		lgCustomes.setWidth100();
		lgCustomes.setHeight100();

		ListGridField lgfObjectId = new ListGridField("Oid", "OID", 30);
		ListGridField lgfOtype = new ListGridField("OType", "ტიპი", 100);
		ListGridField lgfName = new ListGridField("OName", "ტექსტი", 100);
		ListGridField lgfSerial = new ListGridField("serial");
		lgfSerial.setHidden(true);
		lgCustomes.setFields(lgfObjectId, lgfOtype, lgfName, lgfSerial);
		this.addMember(lgCustomes);

		lgCustomes.addDoubleClickHandler(new DoubleClickHandler() {

			@Override
			public void onDoubleClick(DoubleClickEvent event) {
				selectObject();

			}
		});

	}

	private String getType(int type) {
		switch (type) {
		case GissTigerConstants.MOT_BUILDING:
			return "შენობა";
		case GissTigerConstants.MOT_SOCAR:
			return "მილი";
		case GissTigerConstants.MOT_STREET:

			return "გზა";

		default:
			return "";
		}
	}

	private void selectObject() {
		ListGridRecord rec = lgCustomes.getSelectedRecord();
		if (rec == null)
			return;
		String serial = rec.getAttribute("serial");
		if (serial == null)
			return;
		GisMapClickedObject clObj = map.get(serial);
		if (clObj == null)
			return;
		MainPanel.mainPanel.searchContainer.setSelectedMapObject(clObj);
	}

	public void setMapClickedObjects(
			ArrayList<GisMapClickedObject> mapClickedObjects) {
		lgCustomes.setData(new ListGridRecord[] {});
		map.clear();
		ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>();
		for (GisMapClickedObject gisMapClickedObject : mapClickedObjects) {
			String uId = HTMLPanel.createUniqueId();
			map.put(uId, gisMapClickedObject);
			ListGridRecord r = new ListGridRecord();
			r.setAttribute("Oid", gisMapClickedObject.getGid());
			r.setAttribute("OType", getType(gisMapClickedObject.getObj_type()));
			r.setAttribute("OName", gisMapClickedObject.getObj_text());
			r.setAttribute("serial", uId);
			records.add(r);
		}
		lgCustomes.setData(records.toArray(new ListGridRecord[] {}));
	}

}
